//
//  UIButtonViewController.swift
//  Example
//
//  Created by T AO on 2022/2/15.
//

import UIKit
import RxSwift
import RxCocoa

class UIButtonViewController: BaseViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        buttonTap()
        buttonTitleBind()
        isEnabled()
        moreButtonSelected()
    }

}

// MARK: - UIButton

extension UIButtonViewController {
    /// 按钮点击响应
    private func buttonTap() {
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 50, y: 100, width: 200, height: 50)
        button.backgroundColor = .red
        button.setTitle("点击", for: .normal)
        view.addSubview(button)
        
        // 第一种写法
//        button.rx.tap
//            .subscribe(onNext: { [weak self] in
//                self?.showMessage("按钮被点击")
//            })
//            .disposed(by: disposeBag)
        
        // 第二种写法
        button.rx.tap
            .bind { [weak self] in
                self?.showMessage("按钮被点击")
            }
            .disposed(by: disposeBag)
    }
    
    /// 按钮标题（title）的绑定
    private func buttonTitleBind() {
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 50, y: 200, width: 200, height: 50)
        button.backgroundColor = .cyan
        button.setTitle("计数", for: .normal)
        view.addSubview(button)
        
        let timer = Observable<Int>.interval(RxTimeInterval.seconds(1), scheduler: MainScheduler.instance)
        
//        timer
//            .map { "计数：\($0)" }
//            .bind(to: button.rx.title(for: .normal))
//            .disposed(by: disposeBag)
        
        // 富文本
//        timer
//            .map(formatTimeInterval)
//            .bind(to: button.rx.attributedTitle())
//            .disposed(by: disposeBag)
        
        // 按钮图标（image）的绑定
        timer
            .map {
                let name = $0 % 2 == 0 ? "airplane" : "car.fill"
                return UIImage(systemName: name) ?? UIImage()
            }
            .bind(to: button.rx.image())
            .disposed(by: disposeBag)
        
        // 按钮背景图片（backgroundImage）的绑定
//        timer
//            .map {
//                let name = $0 % 2 == 0 ? "cloud.drizzle.fill" : "sun.max.fill"
//                return UIImage(systemName: name) ?? UIImage()
//            }
//            .bind(to: button.rx.backgroundImage())
//            .disposed(by: disposeBag)
    }
    
    /// 按钮是否可用（isEnabled）的绑定
    private func isEnabled() {
        let button = UIButton(type: .system)
        button.frame = CGRect(x: 50, y: 300, width: 100, height: 50)
        button.backgroundColor = .black
        button.setTitle("计数", for: .normal)
        view.addSubview(button)
        
        let switch1 = UISwitch(frame: CGRect(x: 200, y: 300, width: 80, height: 50))
        view.addSubview(switch1)
        
        switch1.rx.isOn
            .bind(to: button.rx.isEnabled)
            .disposed(by: disposeBag)
    }
    
    /// 按钮是否选中（isSelected）的绑定
    private func moreButtonSelected() {
        let button1 = UIButton(type: .system)
        button1.frame = CGRect(x: 50, y: 400, width: 80, height: 30)
        button1.setTitle("button1", for: .normal)
        view.addSubview(button1)
        
        let button2 = UIButton(type: .system)
        button2.frame = CGRect(x: 150, y: 400, width: 80, height: 30)
        button2.setTitle("button2", for: .normal)
        view.addSubview(button2)
        
        let button3 = UIButton(type: .system)
        button3.frame = CGRect(x: 250, y: 400, width: 80, height: 30)
        button3.setTitle("button3", for: .normal)
        view.addSubview(button3)
        
        button1.isSelected = true
        
        let buttons = [button1, button2, button3].map { $0 }
        
        // 创建一个可观察序列，它可以发送最后一次点击的按钮（也就是我们需要选中的按钮）
        let selectedButton = Observable.from(
            buttons.map({ btn in
                btn.rx.tap.map { btn }
            })
        ).merge()
        
        // 对于每一个按钮都对 selectedButton 进行订阅，根据它是否是当前选中的按钮绑定 isSelected 属性
        for button in buttons {
            selectedButton
                .map { $0 == button }
                .bind(to: button.rx.isSelected)
                .disposed(by: disposeBag)
        }
    }
}

extension UIButtonViewController {
    private func showMessage(_ text: String) {
        let alert = UIAlertController(title: text, message: nil, preferredStyle: .alert)
        alert.addAction(UIAlertAction(title: "确定", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
    }
    
    /// 将数字转成对应的富文本
    private func formatTimeInterval(ms: Int) -> NSMutableAttributedString {
        let string = String(format: "%0.2d:%0.2d.%0.1d", [(ms / 600) % 600, (ms % 600) / 10, ms % 10])
        
        let attributedString = NSMutableAttributedString(string: string)
        
        attributedString.addAttribute(NSAttributedString.Key.font, value: UIFont(name: "HelveticaNeue-Bold", size: 16)!, range: NSRange(location: 0, length: 5))
        
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.white, range: NSRange(location: 0, length: 5))
        
        attributedString.addAttribute(NSAttributedString.Key.backgroundColor, value: UIColor.orange, range: NSRange(location: 0, length: 5))
        
        return attributedString
    }
}
